package com.baidu.tcpChatDemo2.thread;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class D01_Callable {
    public static void main(String[] args) throws ExecutionException, InterruptedException {

        //1.子类实现callable接口,并指定返回值类型
        //2.实现call方法
        //3.创建实现类对象
        MyCallable myCallable = new MyCallable(5);
        //4.Thread构造方法只接收Runnable及子类 故用FutureTask包装callable
        FutureTask<String> futureTask = new FutureTask<>(myCallable);
        //5.将futureTask交给线程对象
        Thread thread = new Thread(futureTask);
        //6.执行子线程
        thread.start();
        //7.谁用futureTask对象获取结果数据
        String s = futureTask.get();
        System.out.println("获取到的:" + s);

    }
}

class MyCallable implements Callable<String >{
    private int i;
    public MyCallable(int i){
        this.i = i;
    }

    @Override
    public String call() throws Exception {
        int tmp = 0;
        for (int j = 1; j < i; j++) {
            tmp += j;
        }
        return "子线程累加结果: " + tmp;
    }
}

